package com.laputacastle.dr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.laputacastle.dr.minio.MinioUtil;
import com.laputacastle.dr.model.DemoRecord;
import com.laputacastle.dr.service.DemoRecordService;
import com.laputacastle.dr.service.DrCatalogService;
import com.laputacastle.dr.utils.CommonUtils;
import com.laputacastle.dr.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
public class CatalogMeunController {

    protected static final Logger logger = LoggerFactory.getLogger(CatalogMeunController.class);

    @Autowired
    private DrCatalogService drCatalogService;
    @Autowired
    private DemoRecordService demoRecordService;
    @Autowired
    private MinioUtil minioUtil;

    @Value(value = "${minio.bucket}")
    private String bucketName;
    @Value(value = "${minio.file-folder-name}")
    private String fileFolderFame;

    @RequestMapping("/getContent")
    public Response getContent () {
        String str = "1111![牛牛截图20200115155430.png](http://106.13.135.179:9000/drpro/content/imgs/246b1b85d5b04d8d871889ebf441b905-1579231106676..png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20200117%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20200117T031828Z&X-Amz-Expires=7&X-Amz-SignedHeaders=host&X-Amz-Signature=e26b30080f0233949176c210eda216ff2049e0f6620e32e248f155344b8b802a(http://106.13.135.179:9000/drpro/content/imgs/870baca94bfb4ad795d39fbeb32df996-1579231327487..png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20200117%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20200117T032209Z&X-Amz-Expires=7&X-Amz-SignedHeaders=host&X-Amz-Signature=099bda57f4f642aefb092da831d369bf47d8441085032bbdbd0a4f3ab1589ed1)(http://106.13.135.179:9000/drpro/content/imgs/a3b59af8b8ec4d0eb0225a057a5a7c12-1579239799717..png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20200117%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20200117T054320Z&X-Amz-Expires=7&X-Amz-SignedHeaders=host&X-Amz-Signature=c747fc6d8abcc53c183f484f3829cfea2a5447c9ecaa59010fa28c3432deb939))";
        return Response.success(str);
    }

    @RequestMapping("/getCatalogTreeData")
    public Object getCatalogTreeData(){
        List<Map<String, Object>> catalogTreeData = drCatalogService.getCatalogTreeData();
        return catalogTreeData;
    }

    @RequestMapping("/saveContent")
    public Response saveContent(@RequestParam("contentForm") String submitContent){
        JSONObject obj = (JSONObject) JSON.parse(submitContent);
        demoRecordService.insertSelective(obj);
        return Response.success();
    }

    @RequestMapping("/saveMultipleImg")
    public Object saveImages(@RequestParam("image") MultipartFile[] multipartfiles){
        return this.saveMultipleImg(multipartfiles);
    }

    private String saveSingleImg(MultipartFile multipartfiles) {
        // minio中存储的文件名称
        StringBuilder fileNameSb = new StringBuilder();
        String imgBh = CommonUtils.getUUID();
        String fileName = "";
        String url = "";
        String ext = FileUtils.getExtensionName(multipartfiles.getOriginalFilename()); // 获取文件后缀
        fileNameSb.setLength(0);
        fileNameSb.append(imgBh).append("-").append(System.currentTimeMillis())
                .append(".").append(ext);
        fileName = fileNameSb.toString();
        try {
            InputStream inputStream = multipartfiles.getInputStream();
            url = minioUtil.uploadFile(bucketName, fileFolderFame + fileName, inputStream);
            inputStream.close();
        } catch (IOException e) {
            logger.error("文件上传minio失败!", e);
        }
        return url;
    }

    private Map<String, String> saveMultipleImg(MultipartFile[] multipartfiles) {
        // minio中存储的文件名称
        StringBuffer fileNameSb = new StringBuffer();
        String imgBh = CommonUtils.getUUID();
        Map<String, String> urlsMap= new HashMap<>();
        if(multipartfiles != null && multipartfiles.length>0) {
            for (MultipartFile item : multipartfiles) {
                String ext = FileUtils.getExtensionName(item.getOriginalFilename()); // 获取文件后缀
                String fileName = item.getOriginalFilename(); // 获取文件名
                fileNameSb.setLength(0);
                fileNameSb.append(imgBh).append("-").append(System.currentTimeMillis())
                        .append(".").append(ext);
                String saveFileName = fileNameSb.toString();
                try {
                    InputStream inputStream = item.getInputStream();
                    String url = minioUtil.uploadFile(bucketName, fileFolderFame + saveFileName, inputStream);
                    urlsMap.put(fileName, url);
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("文件上传minio失败!", e);
                }
            }
        }
        return urlsMap;
    }

}
